package com.shuhe;

import com.shuhe.common.CommonFunction;
import com.shuhe.domain.token.Token;
import com.shuhe.handler.*;
import com.shuhe.metastore.*;
import com.shuhe.timer.MyTaskDelData;
import com.shuhe.timer.MyTaskDelLog;
import com.shuhe.timer.MyTaskNew;
import org.apache.log4j.Logger;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.server.handler.ResourceHandler;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.util.resource.Resource;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.util.*;

import static com.shuhe.common.Tools.getConnect;

public class JettyServer {

    private static Logger logger = Logger.getLogger(JettyServer.class);

    public static Server server = null;
    public static Properties globalProperties = new Properties();
    public static Map<String, Token> globalTokens = new HashMap();
    public static String encrypt = "ga";
    public static String algorithmUrl = "http://localhost:8000/algorithm_method";

    public static void main(String[] args) {
        try {
            loadDBConfig();
            initJetty();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static void loadDBConfig() throws  Exception{
        String env = System.getProperty("env", "dev");
        String configFile = "db-" + env + ".properties";
        logger.info("load db config file: " + configFile);
        globalProperties.load(JettyServer.class.getClassLoader().getResourceAsStream(configFile));
        encrypt = globalProperties.getProperty("global.encrypt");
        algorithmUrl = globalProperties.getProperty("global.algorithmUrl");
    }

    public static Token getGlobalToken(String key) {
        return globalTokens.get(key);
    }

    public static void setGlobalToken(String key, Token value) throws Exception {
        globalTokens.put(key, value);
        Connection conn = null;
        try {
            conn = MetaMysql.connect();
            String sql = "select token_id, login_name, user_name, expire_time from common_token " +
                    "where token_id = '" + key + "'";
            ResultSet rs = MetaMysql.querySql(conn, sql);
            if (rs.next()) {
                sql = "update common_token set expire_time = '" + value.getExpire() + "' where token_id = '" + key +
                        "'";
                MetaMysql.execSql(conn, sql);
            } else {
                sql = "insert into common_token(token_id, login_name, user_name, expire_time) values( '" + key + "','" +
                        value.getLoginName() + "','" + value.getUserName() + "','" + value.getExpire() + "')";
                MetaMysql.execSql(conn, sql);
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            CommonFunction.closeDb(conn);
        }
    }

    private static void initGlobalToken() {
        String sql = "select token_id, login_name, user_name, expire_time from common_token";
        Connection conn = null;
        try {
            conn = MetaMysql.connect();
            ResultSet rs = MetaMysql.querySql(conn, sql);
            while (rs.next()) {
                Token token = new Token();
                token.setUserName(rs.getString("user_name"));
                token.setLoginName(rs.getString("login_name"));
                token.setExpire(rs.getString("expire_time"));
                String key = rs.getString("token_id");
                globalTokens.put(key, token);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            CommonFunction.closeDb(conn);
        }
    }


    public static void initJetty() throws Exception {
        Timer timer = new Timer(true);


        //日志删除
        String log_del_status = globalProperties.getProperty("log.del.task.status");
        if (log_del_status.equals("run")) {
            timer.schedule(new MyTaskDelLog(), 0, 24 * 60 * 60 * 1000);  //每天删除20天前的数据
        }
        String data_del_status = globalProperties.getProperty("data.del.task.status");
        //删除2天前业务数据
        if (data_del_status.equals("run")) {
            timer.schedule(new MyTaskDelData(), 0, 24 * 60 * 60 * 1000);  //每天删除2天前的数据
        }


        //每周执行一次，两个库备份
//        timer.schedule(new MyTaskBackKs(), 0, 7 * 24 * 60 * 60 * 1000);

        String status = globalProperties.getProperty("task.status");
        if (status.equals("run")) {
            String period = globalProperties.getProperty("task.run.period");
            String[] parts = period.split(" \\* ");
            long result =
                    Long.parseLong(parts[0]) * Long.parseLong(parts[1]) * Long.parseLong(parts[2]) * Long.parseLong(parts[3]);
            timer.schedule(new MyTaskNew(), 0, result);  //每分钟执行一次
        }

        String runMtqq = globalProperties.getProperty("run.mtqq.task");
        if (runMtqq.equals("run")) {
            MqttClientV5.runAllSource();
        }


        initGlobalToken();

        int port = Integer.parseInt(globalProperties.getProperty("global.port"));
        server = new Server(port);
        ServletContextHandler servletContext = new ServletContextHandler(server, "/servlet");
        servletContext.addServlet(ServiceHandler.class, "/serviceHandler");
        logger.warn("add /serviceHandler");
        servletContext.addServlet(ServiceBusHandler.class, "/serviceBusHandler");
        logger.warn("add /serviceBusHandler");
        servletContext.addServlet(ReportHandler.class, "/reportHandler");
        logger.warn("add /reportHandler");
        servletContext.addServlet(FullTextHandler.class, "/fullTextHandler");
        logger.warn("add /fullTextHandler");
        servletContext.addServlet(MockHandler.class, "/mockHandler/*");
        logger.warn("add /mockHandler");
        servletContext.addServlet(CodeHandler.class, "/codeHandler");
        logger.warn("add /codeHandler");
        servletContext.addServlet(ServiceTestHandler.class, "/serviceTestHandler");
        logger.warn("add /serviceTestHandler");
        servletContext.addServlet(JsonApiHandler.class, "/jsonApiHandler");
        logger.warn("add /jsonApiHandler");
        servletContext.addServlet(DataInHandler.class, "/dataInHandler");
        logger.warn("add /dataInHandler");
        servletContext.addServlet(EditTableHandler.class, "/editTableHandler");
        logger.warn("add /editTableHandler");
        servletContext.addServlet(DataOperateHandler.class, "/dataOperateHandler");
        logger.warn("add /dataOperateHandler");
        servletContext.addServlet(ImportApiHandler.class, "/importApiHandler");
        logger.warn("add /importApiHandler");
        servletContext.addServlet(MetaHandler.class, "/metaHandler");
        logger.warn("add /metaHandler");
        servletContext.addServlet(AiHandler.class, "/aiHandler");
        logger.warn("add /aiHandler");
        servletContext.addServlet(AlarmHandler.class, "/alarmHandler");
        logger.warn("add /alarmHandler");

        String release_system_name = globalProperties.getProperty("release.system.name");
        ContextHandler contextHandler = null;
        if (release_system_name.equals("ga")) {
            contextHandler = new ContextHandler("/prod-api");
        } else {
            contextHandler = new ContextHandler("/pages");
        }

        ResourceHandler resourceHandler = new ResourceHandler();
        resourceHandler.setDirectoriesListed(true);
        resourceHandler.setWelcomeFiles(new String[]{"index.html"});
        resourceHandler.setBaseResource(Resource.newResource(JettyServer.class.getClassLoader().
                getResource("template")));
        contextHandler.setHandler(resourceHandler);

        HandlerList list = new HandlerList();
        list.addHandler(servletContext);
        list.addHandler(contextHandler);

        server.setHandler(list);

        server.start();
        logger.warn("jetty server start " + port);
        server.join();
    }


    public static void stopServer() throws Exception {
        logger.warn("begin stopHandler");
        try {
            server.setStopAtShutdown(true);
            server.setStopTimeout(1000);
            server.stop();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        System.exit(0);
        logger.warn("end stopHandler");
    }


}
